import { GenTableColumnEntity } from '../../entities/gen-table-cloumn.entity';

export const indexVue = (options) => {
  const html = htmlTemplate(options);
  const script = indexScript(options);
  return `
  ${html}
  ${script}
  `;
};

// 所有html模板
const htmlTemplate = ({ moduleName, businessName, columns }) => {
  const searchHtmlStr = getSearchHtmlStr(columns);
  const tableHtmlStr = getTableHtmlStr(moduleName, businessName, columns);
  return `
    <template>
      <div class="app-container">
          ${searchHtmlStr}
          ${tableHtmlStr}
          
          <add-form @update="gGetList" ref="addFormRef"  />
      </div>
    </template>
  `;
};

// 获取搜索模板
const getSearchHtmlStr = (options) => {
  const slotHtmlStr = getSearchSlotHtmlStr(options);
  return `
      <div class="app-container__section" >
        <PlusSearch
            v-bind="getSearchBinds()"
            :columns="columns"
            v-model="searchForm"
        >
        ${slotHtmlStr}
        </PlusSearch>
      </div>`;
};
// 获取表格模板
const getTableHtmlStr = (moduleName, businessName, columns) => {
  const actionBarHtmlStr = getActionBarHtmlStr(moduleName, businessName);
  const tableSlotHtmlStr = getTableSlotHtmlStr(columns);
  return `
      <div class="app-container__section">
      <PlusTable
          v-bind="getBinds()"
          :columns="columns"
      >
        <template #empty>
          <el-empty image-size="100" description="暂无数据"></el-empty>
        </template>
        <template #title>
          <table-title />
        </template>
        <template #toolbar>
          ${actionBarHtmlStr}
          <ClockTimer :task="gGetList" />
          <SearchAreaControl v-model="gShowSearchForm" />
        </template>
        ${tableSlotHtmlStr}
        <template #plus-cell-action="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"  v-hasPermi="['${moduleName}:${businessName}:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']">删除</el-button>
        </template>
      </PlusTable>
    </div>`;
};

// 获取操作区按钮
const getActionBarHtmlStr = (moduleName, businessName) => {
  return `
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['${moduleName}:${businessName}:add']"
        >新增</el-button>
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="gSelection.length !== 1"
            @click="handleUpdate(gSelection[0])" 
            v-hasPermi="['${moduleName}:${businessName}:edit']"
        >修改</el-button>
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="gSelection.length === 0"
            @click="handleDelete"
            v-hasPermi="['${moduleName}:${businessName}:remove']"
        >删除</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['${moduleName}:${businessName}:export']"
        >导出</el-button>
  `;
};


// 获取处理函数的模板
const getFilterStr = (columns) => {
  const filterColumn = columns.filter((item) => {
    return item.isQuery === '1' && item.htmlType === 'datetime';
  });
  if (filterColumn.length === 0) {
    return `return query`;
  } else {
    return `
      const { timeRange, ...rest } = query;
      const params = proxy.formatRangeTime(timeRange, undefined,'YYYY-MM-DD'); 
      return { ...rest, params }
    `;
  }
};

// =========================================================

// 所有的脚本模板
const indexScript = (options) => {
  const { columns, BusinessName, moduleName, functionName, businessName, primaryKey } = options;
  const dictsStr = indexScriptDicts(columns);
  const exportScriptStr = handlerExport(moduleName, businessName);
  const columnsStr = generateColumnsData(columns);
  const filterStr = getFilterStr(columns);

  let script = '';

  script += `
    <script setup name="${BusinessName}">
    import { list${BusinessName}Api, get${BusinessName}Api, del${BusinessName}Api, } from "@/api/${moduleName}/${businessName}";
    import { useTablePage } from '@/hooks/useTablePage.js'
    import { useActions } from '@/hooks/useActions.js'
    import { getCurrentInstance,ref } from "vue"
    import AddForm from './addForm.vue'
    const { proxy } = getCurrentInstance();
    ${dictsStr}
    const primaryKey = "${primaryKey}"  // 主键
    // =============================================
    // 列表请求逻辑
    
    const searchForm = ref({})
    const columns = computed(()=>${columnsStr})
    const {
      gGetList,
      gSelection,
      gShowSearchForm,
      getBinds,
      getSearchBinds
    } = useTablePage(list${BusinessName}Api, {
      searchForm,
      beforeRequest(query){
        ${filterStr}
      }
    })

    // 删除逻辑
    const { deleteAction } = useActions();
    function handleDelete(row) {
      deleteAction({
        api: del${BusinessName}Api,
        uniqueKey:primaryKey,
        selection:row[primaryKey] || gSelection.value
      }).then(() => {
        gGetList();
      });
    }
    
    const addFormRef = ref(null)
    // 新增操作
    const handleAdd = ()=>{
      addFormRef.value.openDialog();
    }
    // 修改操作
    const handleUpdate = (val)=>{
       addFormRef.value.openDialog(val);
    }

    // 导出逻辑
    ${exportScriptStr}
    </script>
    `;

  return script;
};

// 获取类型
const getValueType = (column: GenTableColumnEntity) => {
  // 控件枚举
  const obj = {
    input: 'input',
    textarea: 'textarea',
    select: 'select',
    radio: 'radio',
    checkbox: 'checkbox',
    datetime: 'date-picker',
  };
  const val = obj[column.htmlType];
  if (val) {
    return `valueType:'${val}',`;
  }
  return '';
};

// 获取类型对应关联属性
const getValueTypeAttr = (column: GenTableColumnEntity) => {
  let htmlStr = '';
  if (column.isList === '1') {
    htmlStr += `tableColumnProps: {
          align: 'center'
      },
    `;
  }
  if (['select', 'checkbox', 'radio'].includes(column.htmlType) && column.dictType) {
    htmlStr += `options:${column.dictType}.value,
      optionsMap:{},
    `;
  }
  if (column.htmlType === 'input' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
        maxlength: 200,
        modelModifiers: { trim: true },
      },
    `;
  }
  if (column.htmlType === 'textarea' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
        maxlength: 200,
        showWordLimit: true,
        modelModifiers: { trim: true },
        autosize: { minRows: 2, maxRows: 4 }
      },
    `;
  }
  if (column.htmlType === 'datetime') {
    htmlStr += `
      fieldProps:{
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    `;
  }
  return htmlStr;
};

// 获取表格自定义插槽内容
const getTableSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    const condition1 = item.isList === '1' && ['imageUpload', 'fileUpload', 'editor'].includes(item.htmlType);
    const condition2 = item.isList === '1' && item.dictType;
    return condition1 || condition2;
  });
  let htmlStr = ``;
  filterColumn.forEach((item) => {
    let comStr = '';
    if (item.dictType) {
      if (item.htmlType === 'checkbox') {
        comStr = `<dict-tag :options="${item.dictType}" :value="row.${item.javaField}.split(','):[]"  />`;
      } else {
        comStr = `<dict-tag :options="${item.dictType}" :value="row.${item.javaField}"  />`;
      }
    }
    if (item.htmlType === 'imageUpload') {
      comStr = `<image-preview  :src="row.${item.javaField}"  />`;
    }
    if (item.htmlType === 'fileUpload') {
      comStr = `<el-link type="primary">点击查看文件</el-link>`;
    }
    if (item.htmlType === 'editor') {
      comStr = `
        <el-popover
          placement="bottom"
          :width="200"
          trigger="click"
        >
          <template #reference>
            <el-link type="primary">查看详情</el-link>
          </template>
          <div v-html="row.${item.javaField}"></div>
        </el-popover>
      `;
    }
    htmlStr += `
        <template #plus-cell-${item.javaField}="{ row }">
          ${comStr}
        </template>
    `;
  });
  return htmlStr;
};

// 获取筛选表单自定义插槽内容
const getSearchSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    return item.isQuery === '1' && item.htmlType === 'datetime';
  });
  if (filterColumn.length === 0) {
    return ``;
  }
  const item = filterColumn[0];
  return `
      <template #plus-field-${item.javaField}>
           <el-date-picker  start-placeholder="开始时间" end-placeholder="结束时间"  v-model="searchForm.timeRange" type="daterange"  />
      </template>
  `;
};



// 生成列信息
const generateColumnsData = (columns: GenTableColumnEntity[]) => {
  let str = `[`;
  columns.filter(item=>item.isList === '1').forEach((item) => {
    str += `{
      label: '${item.columnComment}',
      prop: '${item.javaField}',
      hideInSearch:${item.isQuery !== '1'},
      ${getValueType(item)}
      ${getValueTypeAttr(item)}
    },`;
  });
  str += `
    {
      label: '操作',
      prop: 'action',
      minWidth: '120px',
      hideInSearch: true,
      hideInForm: true,
      tableColumnProps: {
        align: 'center',
        fixed: 'right'
      }
    }
  `;
  str += `]`;
  return str;
};



// 导出脚本模板
const handlerExport = (moduleName, businessName) => {
  const h = `const  handleExport = () =>{
         proxy.download(
          '${moduleName}/${businessName}/export',
          {...searchForm.value},
          \`${businessName}_\$\{new Date().getTime()\}.xlsx\`
         )
     }`;
  return h;
};

// 字典获取脚本模板
export const indexScriptDicts = (columns) => {
  let script = '';
  const dicts = [];
  columns.forEach((item) => {
    if (item.dictType != '') {
      dicts.push(item.dictType);
    }
  });
  const noRepeatDict = [...new Set(dicts)];
  if (noRepeatDict.length > 0) {
    script += `const { ${noRepeatDict.toString()} } = proxy.useDict(${"'" + noRepeatDict.join("','") + "'"});`;
  } else {
    script += ``;
  }
  return script;
};

